package com.zlm.config;

import com.zlm.service.MyUserDetailsServiceImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;


/**
 * 自己配置spring security的配置类
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private MyUserDetailsServiceImpl myUserDetailsService;

    /**
     * 默认使用内存数据源的话
     * @return
     * @throws Exception
     */
    /*@Bean
    @Override
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
        userDetailsService.createUser(User.withUsername("root").password("{noop}1234").roles("admin").build());
        return userDetailsService;
    }*/

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/login.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html") // 指定自定义登录页面
                .loginProcessingUrl("/doLogin") // 登录请求的地址
                .usernameParameter("uname") // 后面去取的时候的东西
                .passwordParameter("pwd") // 后面去取的时候的东西
                .defaultSuccessUrl("/index.html", true) // 登录成功后默认跳转的 true就是总是
                .failureUrl("/login.html") // 重定向到login.html  加上forward的都是request请求
                .and()
                .logout() // 开启退出登录
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")
                .and()
                .csrf().disable(); // csrf漏洞保护
    }
}
